package com.longrise.android.byjk.plugins.dealsituation.cachecourse.downloadeddetail;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.DownloadedDetailBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.upload_offline.DBHelper;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadService;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/4/6.
 * 下载详情presenter
 */

public class DownloadedDetailPresenter extends DownloadedDetailContract.Presenter {


    private static final String TAG = "DownloadedDetailPresenter";
    private DBHelper mDbHelper;
    private DownloadManager mDownloadManager;
    private String mCourseId;
    private List<String> mStartOrStopList = new ArrayList<>(); //需要开始的url集合


    @Override
    public void init() {
        mDbHelper = new DBHelper(mContext);
        mDownloadManager = DownloadService.getDownloadManager();
        mView.initRcv(mDownloadManager);
    }

    @Override
    void initData(String courseId) {
        this.mCourseId = courseId;
        getData();
    }

    private void getData() {
        Observable.create(new ObservableOnSubscribe<DownloadedTransferBean>() {
            @Override
            public void subscribe(ObservableEmitter<DownloadedTransferBean> e) throws Exception {
                e.onNext(getDataFromDB());
                e.onComplete();
            }
        }).filter(new Predicate<DownloadedTransferBean>() {
            @Override
            public boolean test(DownloadedTransferBean bean) throws Exception {
                return bean.isSuccess();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DownloadedTransferBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mView.showLoading();
                    }

                    @Override
                    public void onNext(DownloadedTransferBean bean) {
                        mView.updateData(bean, mDownloadManager);
                        PrintLog.d(TAG, bean.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        mView.dismissLoading();
                    }
                });
    }

    /**
     * 从数据库获取已下载和正在下载的数据
     */
    private DownloadedTransferBean getDataFromDB() {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        DownloadedTransferBean trsbean = new DownloadedTransferBean();
        List<DownloadedDetailBean> downloadedList = trsbean.getDownloadedList();
        List<DownloadedDetailBean> downloadingList = trsbean.getDownloadingList();
        try {
            db = mDbHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                            " where userID = ? and courseID = ? order by position asc ",
                    new String[]{UserInfor.getInstance().getUserid(), mCourseId});
            while (cursor.moveToNext()) {
                String mCourseName = cursor.getString(cursor.getColumnIndex("courseName"));
                String downloadurl = cursor.getString(cursor.getColumnIndex("downloadurl"));
                String partpath = cursor.getString(cursor.getColumnIndex("partpath"));
                String chapterName = cursor.getString(cursor.getColumnIndex("chapterName"));
                String cwName = cursor.getString(cursor.getColumnIndex("cwName"));
                String cwId = cursor.getString(cursor.getColumnIndex("cwID"));
                String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
                String chapterid = cursor.getString(cursor.getColumnIndex("chapterid"));
                int videopass = cursor.getInt(cursor.getColumnIndex("videopass"));
                int hasqa = cursor.getInt(cursor.getColumnIndex("hasqa"));
                int isfinished = cursor.getInt(cursor.getColumnIndex("isfinished"));
                int position = cursor.getInt(cursor.getColumnIndex("position"));
                String pathno = cursor.getString(cursor.getColumnIndex("pathno"));

                DownloadedDetailBean bean = new DownloadedDetailBean();
                bean.setPathnojd(pathno);
                bean.setPosition(position);
                bean.setUrl(downloadurl);
                bean.setPartPath(partpath);
                bean.setChapterName(chapterName);
                bean.setCwName(cwName);
                bean.setCachepath(cachepath);
                if (videopass == 0) {
                    bean.setVideopass(false);
                } else {
                    bean.setVideopass(true);
                }
                if (hasqa == 0) {
                    bean.setHasqa(false);
                } else {
                    bean.setHasqa(true);
                }
                if (isfinished == 0) {
                    bean.setIsfinish(false);
                } else {
                    bean.setIsfinish(true);
                }

                long totalLength = 0;
                mDownloadManager.getFileSize(downloadurl);
                bean.setTotalLength(totalLength);
                bean.setCwId(cwId);
                bean.setChapterId(chapterid);
                boolean hasDownloaded = FileUtil.isHasDownloaded(mContext, UserInfor.getInstance().getUserid(), cwId);
                if (hasDownloaded) {
                    bean.setStatus(DownloadedDetailBean.FINISH);
                    downloadedList.add(bean);
                } else {
                    downloadingList.add(bean);
                }
            }
            addAndInitTask(downloadingList);
            //----------组合rcv数据----------
            List<MultiItemEntity> rcvDataList = trsbean.getRcvDataList();
            DownloadedDetailTitleItem item1_1 = new DownloadedDetailTitleItem(AppUtil.getString(R.string.downloaded_zzhc));
            for (int i = 0; i < downloadingList.size() + 1; i++) { //因为有个全部课程按钮 所以数量+1
                DownloadedDetailChildItem item2_1 = new DownloadedDetailChildItem(true, i);
                item1_1.addSubItem(item2_1);
            }
            DownloadedDetailTitleItem item1_2 = new DownloadedDetailTitleItem(AppUtil.getString(R.string.downloaded_yhc));
            for (int j = 0; j < downloadedList.size(); j++) {
                DownloadedDetailChildItem item2_2 = new DownloadedDetailChildItem(false, j);
                item1_2.addSubItem(item2_2);
            }
            rcvDataList.add(item1_1);
            rcvDataList.add(item1_2);
            //------------------------------
            trsbean.setSuccess(true);
        } catch (Exception e) {
            trsbean.setSuccess(false);
        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
            return trsbean;
        }
    }

    /**
     * 如果因版本升级未将url添加进filedownloader的 现在添加
     */
    private void addAndInitTask(List<DownloadedDetailBean> list) {
        for (DownloadedDetailBean bean : list) {
            String url = bean.getUrl();
            String cachepath = bean.getCachepath();
            mDownloadManager.addAndInitTask(url, cachepath);
        }
    }

    @Override
    public void isAbleStudy(final DownloadedDetailBean downloadedDetailBean, final int position
            , final int status, final List<DownloadedDetailBean> downloadingList) {
        DZZWTools.showWaitDialog(mContext);
        UserInfor userInfor = UserInfor.getInstance();
        EntityBean coursEntityBean = new EntityBean();
        coursEntityBean.set("cardno", userInfor.getUsersfzh());
        coursEntityBean.set("courseid", mCourseId);
        EntityBean argBean = new EntityBean();
        argBean.set("bean", coursEntityBean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_course_sTrainResDirStructBean", argBean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
//                if (mIsFinish) return;
                EntityBean res_ = (EntityBean) result;
                if (res_ != null) {
                    if (res_.getInt("resultstate") == 1) {
                        EntityBean parseResult = res_.getBean("result");
                        //是否已经开通
                        boolean issinguptrain = parseResult.getBoolean("issinguptrain");
                        //是否能够学习
                        boolean isablestudy = parseResult.getBoolean("isablestudy");
                        //是否关闭
                        boolean isclose = parseResult.getBoolean("isclose");
                        //是否已经关闭
                        boolean isablesignup = parseResult.getBoolean("isablesignup");
                        //是否可以延期
                        boolean isabledelaycourse = parseResult.getBoolean("isabledelaycourse");
                        EntityBean traindirstruct = parseResult.getBean("traindirstruct");
                        boolean ispass = traindirstruct.getBoolean("ispass", false);

                        if (isclose) {
                            //已下架
                            DZZWTools.showToast(mContext, mContext.getString(R.string.download_course_yxj), Toast.LENGTH_SHORT);
                        } else {//不可以学习
                            if (!isablestudy) {
                                if (issinguptrain && !isabledelaycourse && !isablesignup) { //购买过，不可以延期， 不可以报名 已关闭状态
                                    if (ispass) {  //已过期
                                        DZZWTools.showToast(mContext, mContext.getString(R.string.course_state_is_gq), Toast.LENGTH_SHORT);
                                    } else {       //已关闭
                                        DZZWTools.showToast(mContext, mContext.getString(R.string.download_course_ygb_), Toast.LENGTH_SHORT);
                                    }
                                } else {
                                    DZZWTools.showToast(mContext, mContext.getString(R.string.course_state_is_gq), Toast.LENGTH_SHORT);
                                }
                            } else {
                                if (status == DownloadedDetailActivity.DOWNLOADSTATUS) {
                                    judgeNetwork(downloadedDetailBean);
                                } else if (status == DownloadedDetailActivity.STUDYSTATUS) {
//                                      toPlay(downloadedDetailBean);
                                } else if (status == DownloadedDetailActivity.DOWNLOADALLSTATUS) {
                                     toStartAll(downloadingList);
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, mContext.getString(R.string.networkerror), Toast.LENGTH_SHORT);
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null); //不能在finished中调用   sjz
            }
        });

    }

    private void judgeNetwork(final DownloadedDetailBean downloadedDetailBean) {
        //判断有没有网络
        if (!NetUtil.checkNetEnable()) {
            return;
        }
        String url = downloadedDetailBean.getUrl();
        DownloadManager.DownloadStatus status = mDownloadManager.getStatus(url);
        if (DownloadManager.DownloadStatus.DOWNLOADING.equals(status)) { //正在下载的点击直接暂停不用判断是否是移动网络
            startItem(downloadedDetailBean);
        } else {
            boolean canMobileDownload = Control.isCanMobileDownload();
            //判断当前网络是否是移动网络
            if (!canMobileDownload && NetUtil.isDataNet()) {
                mView.showDownloadNetTips(downloadedDetailBean);
            } else {
                startItem(downloadedDetailBean);
            }
        }
    }

    /**
     * 开始所选下载的项目
     */
    @Override
    public void startItem(DownloadedDetailBean downloadedDetailBean) {
        String url = downloadedDetailBean.getUrl();
        boolean b = mDownloadManager.switchStatus(url);
        if (!b) {
            String cachepath = downloadedDetailBean.getCachepath();
            mDownloadManager.addTask(url, cachepath);
        }
    }

    /**
     * 未下载完成的item 全部开始下载 或者全部暂停
     */
    @Override
    public void stopOrStart(int allDownloadStatus, List<DownloadedDetailBean> downloadingList) {
        if (allDownloadStatus == DownloadedDetailActivity.START) {
            mStartOrStopList.clear();
            for (int x = 0; x < downloadingList.size(); x++) {
                DownloadedDetailBean downloadedDetailBean = downloadingList.get(x);
                String url = downloadedDetailBean.getUrl();
                mStartOrStopList.add(url);
            }
            mDownloadManager.stopAll(mStartOrStopList);
            mView.setAllDownloadStatus(DownloadedDetailActivity.STOP);
        } else {
            isAbleStudy(null, 0, DownloadedDetailActivity.DOWNLOADALLSTATUS,downloadingList);
        }
    }

    /**
     * 全部开始
     */
    private void toStartAll(List<DownloadedDetailBean> downloadingList) {
        mStartOrStopList.clear();
        for (int y = 0; y < downloadingList.size(); y++) {
            DownloadedDetailBean downloadedDetailBean = downloadingList.get(y);
            String url = downloadedDetailBean.getUrl();
            mStartOrStopList.add(url);
        }
        mDownloadManager.startAll(mStartOrStopList);
        mView.setAllDownloadStatus(DownloadedDetailActivity.START);
    }
}
